package de.zainodis.kitchengnome.domainmodel.persistence;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import de.zainodis.commons.LogCat;
import de.zainodis.kitchengnome.domainmodel.ItemList;
import de.zainodis.kitchengnome.domainmodel.ListItem;
import de.zainodis.kitchengnome.domainmodel.Suggestion;

/**
 * Manages the database and related DAOs.
 * 
 * @author fzarrai
 * 
 */
public class DatabaseManager extends OrmLiteSqliteOpenHelper {
	private static final String TAG = "DatabaseManager";

	/** Any time database objects change, this version MUST be incremented */
	private static final int DATABASE_VERSION = 1;

	/** Name of the applications database file */
	private static String DATABASE_NAME = "kitchengnome.db";

	private IListItemDao listItemDao = null;
	private ISuggestionDao suggestionDao = null;
	private IItemListDao itemListDao = null;

	public DatabaseManager(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		try {
			LogCat.i(TAG, "Creating database...");

			TableUtils.createTable(connectionSource, ListItem.class);
			TableUtils.createTable(connectionSource, ItemList.class);
			TableUtils.createTable(connectionSource, Suggestion.class);

		} catch (SQLException e) {
			LogCat.e(TAG, "Failed to create database.");
		}
	}

	public IListItemDao getListEntryDao() throws SQLException {
		if (listItemDao == null) {
			listItemDao = getDao(ListItem.class);
		}
		return listItemDao;
	}

	public ISuggestionDao getSuggestionDao() throws SQLException {
		if (suggestionDao == null) {
			suggestionDao = getDao(Suggestion.class);
		}
		return suggestionDao;
	}

	public IItemListDao getItemListDao() throws SQLException {
		if (itemListDao == null) {
			itemListDao = getDao(ItemList.class);
		}
		return itemListDao;
	}

	@Override
	public void close() {
		super.close();
		listItemDao = null;
		suggestionDao = null;
		itemListDao = null;
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2, int arg3) {
		// Implement once required
	}
}
